//
//  BookmarkCatalogView.m
//  ebook
//
//  Created by 吴超飞 on 16/1/26.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "BookmarkCatalogView.h"
#import "UIView+Extension.h"
#import "MJRefresh.h"
#import "ReaderBook.h"
#import "UIView+Extension.h"
#import "FileManager.h"
#import "Book.h"
#import "EbookNetRequest.h"
#import "UIImage+RTTint.h"
#import "DownloadManager.h"

@interface BookmarkCatalogView()<UITableViewDataSource,UITableViewDelegate>{
    
    BOOL isDesc,isNeedScrollTop;
    int currentpage;
}

@property (nonatomic,retain) UIView *bgView;
@property (nonatomic,retain) UILabel *totoalLabel;
@property (nonatomic,retain) UILabel *titleLabel;
@property (nonatomic,retain) UIButton *descBtn;
@property (nonatomic,retain) UIImageView *switchImageView;
@property (nonatomic,strong) NSArray *chaptersDataArray;//目录
@property (nonatomic,weak  ) ReaderBookModel *readerBookModel;
@property (nonatomic,retain) Book *book;
@property (nonatomic,retain) UISlider *slider;

@property (nonatomic,retain) UIColor *normalColor;
@property (nonatomic,retain) UIColor *selectedColor;
@property (nonatomic,retain) UIColor *grayColor;

@end

#define kTotalLabelHeight 35
#define kTitleLabelHeight 25
#define YSpace (iPhoneX?24:0)

@implementation BookmarkCatalogView

-(id)initWithDataControler:(ReaderBookModel *)readerbookModel{
    
    _readerBookModel = readerbookModel;
    _book = _readerBookModel.readerBook.book;
    
    self = [super initWithFrame:CGRectMake(0, 0, MTScreenW-40, MTScreenH)];
    
    if (self) {
        
        [self setUI];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshChapterList:) name:kGetChapterListCompleteNotification object:nil];
    [[ReaderGlobalModel shareModel].readerConfig addObserver:self forKeyPath:@"BgColorType" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    
    return self;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"BgColorType"]) {
        
        _bgView.backgroundColor = [self getBgcolor:YES];
        _tableview.backgroundColor = [self getBgcolor:NO];
        self.tableview.separatorColor =
        MTConfigColor([ReaderGlobalModel shareModel].readerConfig.IsNight?@"MTBookMarkCatalog_tableviewSeparatorNight_Color":@"MTBookMarkCatalog_tableviewSeparatorDay_Color");
        self.titleLabel.textColor = self.normalColor;
        self.totoalLabel.textColor = self.grayColor;
        _tableview.layer.borderColor = _tableview.separatorColor.CGColor;
        
        //设置滑块图标图片
        UIImage *slImg = [self imageByApplyingAlpha:0.7 image:[UIImage imageNamed:@"mulu_huadong_sl"]];
        UIImage *thumbImg = [ReaderGlobalModel shareModel].readerConfig.IsNight?[UIImage imageNamed:@"mulu_huadong_nl"]:slImg;
        [_slider setThumbImage:thumbImg forState:UIControlStateNormal];
        //设置点击滑块状态图标  滑动不显示，否则图标会跳动
        [_slider setThumbImage:thumbImg forState:UIControlStateHighlighted];
    }
}

- (void)blindingRefresh{
    
    __unsafe_unretained __typeof(self) weakSelf = self;
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        isNeedScrollTop = YES;
        __strong __typeof(self) strongSelf = weakSelf;
        [strongSelf.readerBookModel checkUpdateAndGetchapterlist:^(NSArray *list,BOOL needReload) {
            _chaptersDataArray = list;
            dispatch_async(dispatch_get_main_queue(), ^{
                if(needReload){
                    [strongSelf reloadData];
                }else{
                    [strongSelf.tableview.mj_header endRefreshing];
                }
            });
        }];
    }];
    self.tableview.mj_footer.automaticallyHidden = YES;
}

- (void)setUI {
    
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20+kTitleLabelHeight+kTotalLabelHeight+YSpace)];
    _bgView.backgroundColor = [self getBgcolor:YES];
    [self insertSubview:_bgView atIndex:0];
    
    self.titleLabel.text = _book.bookname;
    self.titleLabel.frame = CGRectMake(15, 20+YSpace, [self widthOfTittleText:_titleLabel.text], kTitleLabelHeight);
    [_bgView addSubview:self.titleLabel];
    [_bgView addSubview:self.totoalLabel];
    [_bgView addSubview:self.descBtn];
    
    float tableY = CGRectGetMaxY(self.totoalLabel.frame);
    UITableView *tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, tableY, self.frame.size.width, self.frame.size.height - tableY) style:UITableViewStylePlain];
    tableview.delegate = self;
    tableview.dataSource = self;
    tableview.backgroundColor = [self getBgcolor:NO];
    tableview.separatorInset = UIEdgeInsetsMake(15,0,0,0);
    tableview.separatorColor = [ReaderGlobalModel shareModel].readerConfig.IsNight? MTConfigColor(@"MTBookMarkCatalog_tableviewSeparatorNight_Color"):MTConfigColor(@"MTBookMarkCatalog_tableviewSeparatorDay_Color");
    tableview.showsVerticalScrollIndicator = NO;
    [self insertSubview:tableview atIndex:1];
    _tableview = tableview;
    _tableview.layer.borderColor = _tableview.separatorColor.CGColor;
    
    [self blindingRefresh];
    //    [self showHUD];//显示加载框
    
    //得到透明的图片
    UIImage *img = [self imageByApplyingAlpha:0 image:[UIImage imageNamed:@"mulu_huadong_sl"]];
    
    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0,0,self.height-tableY,img.size.width/2)];
    
    //设置未滑动位置背景图片
    [slider setMinimumTrackImage:img forState:UIControlStateNormal];
    //设置已滑动位置背景图
    [slider setMaximumTrackImage:img forState:UIControlStateNormal];
    //设置滑块图标图片
    UIImage *slImg = [self imageByApplyingAlpha:0.7 image:[UIImage imageNamed:@"mulu_huadong_sl"]];
    UIImage *thumbImg = [ReaderGlobalModel shareModel].readerConfig.IsNight?[UIImage imageNamed:@"mulu_huadong_nl"]:slImg;
    [slider setThumbImage:thumbImg forState:UIControlStateNormal];
    //设置点击滑块状态图标  滑动不显示，否则图标会跳动
    [slider setThumbImage:thumbImg forState:UIControlStateHighlighted];
    
    //设置旋转90度
    slider.transform = CGAffineTransformMakeRotation(M_PI_2);
    CGPoint cp = CGPointMake(CGRectGetMaxX(self.descBtn.frame)-slider.width/2-2, tableview.centerY);
    slider.center = cp;
    //设置起始位置
    //slider.value=0.5;
    //设置背景颜色
    slider.backgroundColor = [UIColor clearColor];
    [slider addTarget:self action:@selector(sliderChange) forControlEvents:UIControlEventValueChanged];
    [self addSubview:slider];
    _slider = slider;
}

-(float)widthOfTittleText:(NSString *)tittle{
    
    return [tittle sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font}].width;
}

-(UILabel *)titleLabel{
    
    if(!_titleLabel){
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.font = [UIFont systemFontOfSize:18];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = self.normalColor;
        _titleLabel = titleLabel;
    }
    return _titleLabel;
}

-(UILabel *)totoalLabel{
    
    if(!_totoalLabel){
        UILabel *totoalLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.titleLabel.frame), self.frame.size.width/2, kTotalLabelHeight)];
        totoalLabel.textAlignment = NSTextAlignmentLeft;
        totoalLabel.font = [UIFont systemFontOfSize:14];
        totoalLabel.textColor = self.grayColor;
        _totoalLabel = totoalLabel;
    }
    
    return _totoalLabel;
}

-(UIButton *)descBtn{
    
    if (!_descBtn) {
        _descBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width - 15 - 50, CGRectGetMaxY(self.titleLabel.frame), 50, 30)];
        _descBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _descBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_descBtn addTarget:self action:@selector(descBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _descBtn.selected = !isDesc;
    }
    [_descBtn setImage:[[UIImage imageNamed:@"sort_zhengxu"] rt_tintedImageWithColor:self.selectedColor] forState:UIControlStateNormal];
    [_descBtn setImage:[[UIImage imageNamed:@"sort_daoxu"] rt_tintedImageWithColor:self.selectedColor] forState:UIControlStateSelected];
    
    return _descBtn;
}

/**
 *  转换图片
 */
- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha image:(UIImage*)image
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextSetAlpha(ctx, alpha);
    CGContextDrawImage(ctx, area, image.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

-(UIColor *)getBgcolor:(BOOL)isHead{
    
    return [ReaderGlobalModel shareModel].readerConfig.IsNight?(isHead?ChapterListNightTittleBg : ChapterListNightContentBg):[UIColor whiteColor];
}

#pragma mark -

//获取并加载数据
- (void)reloadData{
    
    //获取章节下载状态比较耗时，需加入进度提示
    UIActivityIndicatorView *indicateView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self addSubview:indicateView];
    indicateView.center = self.center;
    [indicateView startAnimating];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *cArray = [NSMutableArray arrayWithArray:_readerBookModel.readerBook.chapterList];
        _chaptersDataArray = [self sortAndMarkdownArray:cArray];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [indicateView stopAnimating];
            [indicateView removeFromSuperview];
            [self.tableview reloadData];
            [self refreshBookInfo];
            [self scrollTableViewToRow];
            [self.tableview.mj_header endRefreshing];
        });
    });
}

//根据通知刷新章节列表,最后一页才刷新
- (void)refreshChapterList:(NSNotification *)noti {
    
    if(self.tableview)
        [self reloadData];
}
//刷新书籍信息
-(void)refreshBookInfo{
    _book = _readerBookModel.readerBook.book;
    self.titleLabel.text = _book.bookname;
    self.totoalLabel.text = [NSString stringWithFormat:@"本书共%d章",(int)_chaptersDataArray.count];
    [self.totoalLabel setNeedsDisplay];
}

-(void)sliderChange {
    
    if (!_chaptersDataArray || _chaptersDataArray.count == 0) return;
    [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(_chaptersDataArray.count-1)*_slider.value inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat y = scrollView.contentOffset.y/(scrollView.contentSize.height-_tableview.height);
    _slider.value = y;
    
    _tableview.layer.borderWidth = scrollView.contentOffset.y == 0?0:0.5;
}

- (void)scrollTableViewToRow {
    
    if (isNeedScrollTop){//滚动到第一行
        
        if (!_chaptersDataArray || _chaptersDataArray.count == 0)return;
        [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        isNeedScrollTop = NO;
        _slider.value = 0;
    }else{
        
        //row: 当前阅读到的行号
        NSInteger row = 0 ;
        if (_chaptersDataArray.count == 0 || !_chaptersDataArray)return;
        for (Chapter *chapter in _chaptersDataArray) {
            if ([chapter.chapterid isEqualToString:_readerBookModel.readerBook.chapter.chapterid]) {
                row = [_chaptersDataArray indexOfObject:chapter];
                break;
            }
        }
        
        if (row>_chaptersDataArray.count-1) return;//数组越界返回
        [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        _slider.value = ((float)row)/_chaptersDataArray.count; //slider 位置为row行对应的比例
    }
}

//正序逆序排列数据并标识是否已下载
- (NSArray *)sortAndMarkdownArray:(NSArray *)array {
    
    if([self isNeedResort:array]){
        array = [array sortedArrayUsingComparator:^NSComparisonResult(Chapter *obj1, Chapter *obj2) {
            //根据chapterorder字段排序，老版中已缓存列表中没有这个字段的直接根据chapterid排
            NSComparisonResult result = isDesc?[obj1.chapterorder integerValue]<[obj2.chapterorder integerValue]:[obj1.chapterorder integerValue]>[obj2.chapterorder integerValue];
            if(result==NSOrderedSame)
                result = isDesc?[obj1.chapterid integerValue]<[obj2.chapterid integerValue]:[obj1.chapterid integerValue]>[obj2.chapterid integerValue];
            return result;
        }];
    }
    
    NSArray *localDownArray = [FileManager readBookChapters:_book];
    [array enumerateObjectsUsingBlock:^(Chapter *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //存在章节内容的文件且不是无效内容的才显示为已下载
        if([localDownArray containsObject: obj.chapterid]){
            //网络错误提示文件大小为0.041016k,先做大小判断
            if([FileManager fileSizeOfContentBook:_book chapterId:obj.chapterid]>0.1){
                obj.isInLocal = YES;
            }else{
                NSString *content = [FileManager readContentBook:_book chapterId:obj.chapterid];
                if(![[DownloadManager shareInstance] isErrorContent:content]){
                    obj.isInLocal = YES;
                }else{
                    obj.isInLocal = NO;
                }
            }
        }else{
            obj.isInLocal = NO;
        }
    }];
    return array;
}

-(BOOL)isNeedResort:(NSArray *)array{
    
    BOOL ret = NO;
    Chapter *firtst = [array firstObject];
    Chapter *last = [array lastObject];
    if(isDesc&&([firtst.chapterorder intValue]<[last.chapterorder intValue]||([firtst.chapterorder intValue]==[last.chapterorder intValue]&&[firtst.chapterid intValue]<[last.chapterid intValue]))){//逆序时，当前数据是正序的
        ret = YES;
    }
    if (!isDesc&&([firtst.chapterorder intValue]>[last.chapterorder intValue]||([firtst.chapterorder intValue]==[last.chapterorder intValue]&&[firtst.chapterid intValue]>[last.chapterid intValue]))) {//正序时，当前数据是逆序的
        ret = YES;
    }
    
    return ret;
}

#pragma mark - UITableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0f;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  self.chaptersDataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    for (UIView *subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    
    if(_chaptersDataArray.count == 0 )return cell;
    
    Chapter *chapter;
    id obj = _chaptersDataArray[indexPath.row];
    if([obj isKindOfClass:[Chapter class]]){
        chapter=(Chapter *)obj;
    }else{
        return cell;
    }
    
    float chapterLabelX = 15;
    float chapterMarginRight = 60;
    UILabel *chapterLabel = [[UILabel alloc] initWithFrame:CGRectMake( chapterLabelX, 0 ,self.frame.size.width - chapterMarginRight - chapterLabelX, 44)];
    chapterLabel.textAlignment = NSTextAlignmentLeft;
    chapterLabel.numberOfLines = 1;
    chapterLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    chapterLabel.textColor = self.normalColor;
    chapterLabel.font = [UIFont systemFontOfSize:15];
    if(chapter)chapterLabel.text = chapter.chaptername;
    [cell.contentView addSubview:chapterLabel];
    
    UILabel *readedLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-chapterMarginRight, 0, 50, 44)];
    readedLabel.textAlignment = NSTextAlignmentRight;
    readedLabel.textColor = self.grayColor;
    readedLabel.font = [UIFont systemFontOfSize:12];
    readedLabel.text = @"已下载";
    if (chapter.isInLocal) {
        [cell.contentView addSubview:readedLabel];
    }
    
    BOOL isCurrentChapter = [chapter.chapterid intValue]==[_readerBookModel.readerBook.chapter.chapterid intValue];
    if (isCurrentChapter) {
        chapterLabel.textColor = self.selectedColor;
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        _totoalLabel.text = [NSString stringWithFormat:@"本书共%d章", (int)_chaptersDataArray.count];
    }
}

-(UIColor *)selectedColor{
    return MTConfigColor([ReaderGlobalModel shareModel].readerConfig.IsNight?@"MTReaderBar_NightSelected_Color":@"MTReaderBar_DaySelected_Color");
}

-(UIColor *)normalColor{
    return MTConfigColor([ReaderGlobalModel shareModel].readerConfig.IsNight?@"MTBookMarkCatalog_NightNomarlText_Color":@"MTBookMarkCatalog_DayNomarlText_Color");
}

-(UIColor *)grayColor{
    return MTConfigColor([ReaderGlobalModel shareModel].readerConfig.IsNight?@"MTBookMarkCatalog_NightGrayText_Color":@"MTBookMarkCatalog_DayGrayText_Color");
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([self.delegate respondsToSelector:@selector(bookmarkCatalogView:didSelectedRowObject:)]) {
        
        id selectedObj = indexPath.row < self.chaptersDataArray.count? self.chaptersDataArray[indexPath.row]:nil;
        
        if(selectedObj)
            [self.delegate bookmarkCatalogView:self didSelectedRowObject:selectedObj];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self reloadData];
    });
}

#pragma mark - 事件处理

-(void)descBtnClick:(UIButton*)btn{
    
    isDesc = !isDesc;
    _descBtn.selected = !isDesc;
    isNeedScrollTop = isDesc;
    [self reloadData];
}

-(void)didReceiveMemoryWarningOperator{
    _chaptersDataArray = nil;
}

-(void)dealloc{
    
    [[ReaderGlobalModel shareModel].readerConfig removeObserver:self forKeyPath:@"BgColorType"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
